package iscript.gameFramework.NetService.core 
{
	import adobe.utils.CustomActions;
	import be.boulevart.as3.security.RC4;
	import flash.utils.ByteArray;
	import flash.events.*;
	import flash.events.EventDispatcher;
	import flash.net.Socket
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import iscript.coreFramework.debug.ArthropodDebug;
	import iscript.gameFramework.NetService.data.NetMessageBase;
	import iscript.gameFramework.NetService.ServiceProxy;
	import iscript.gameFramework.NetService.data.BufferList;
	import iscript.gameFramework.NetService.data.KeyTable;
	import iscript.gameFramework.NetService.util.BigInt;
	import iscript.gameFramework.NetService.util.ProtocolUtils;
	/**
	 * ...
	 * @author raymond
	 */
	public class ServerEntity extends EventDispatcher
	{	
		private var _socket:Socket;
		private var _connected:Boolean;		
		private var _buffer:ByteArray;
		private var _ip:String;
		private var _port:int;
		public function ServerEntity()
		{
			init();
			_socket = new Socket();
		}
		
	    private function init():void {
		    _buffer = new ByteArray();
		}
		
		public function connect(ip:String, port:int):void {			
			_ip = ip;
			_port = port;
			_socket.addEventListener(Event.CONNECT, onConnect);
			_socket.addEventListener(ProgressEvent.SOCKET_DATA,_getSocketData);
			_socket.addEventListener(Event.CLOSE, onClose);
			_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);	
			_socket.connect(ip, port);
			}
			
		private function onIOError(e:IOErrorEvent):void 
		{
			ServiceProxy.instance.dispatchEvent(new Event(ServiceProxy.ERROR));
			trace("socket发送通信异常:" + e.text);
		}
			
		private function onSecurityError(e:SecurityErrorEvent):void 
		{
			ServiceProxy.instance.dispatchEvent(new Event(ServiceProxy.ERROR));
			trace("socket发送沙箱异常:" + e.text);
		}
			
		private function onConnect(e:Event):void 
		{	
			_sendTGWPackData(ServiceProxy.instance.TGWPackData, "GBK");
			ServiceProxy.instance.dispatchEvent(new Event(ServiceProxy.ConnectSuccess));
		}
		/**
		 * 发送TGW包头协议
		 */
		/* private function sendTGWLogic():void
		{
			var httpHead:String = "GET / HTTP/1.1\r\nHost: " + _ip + ":" + _port + "\r\n\r\n";
			_socket.writeMultiByte(httpHead,"GBK");
			_socket.flush();
			trace("发送TGW:" + httpHead);
		} */
		private function onClose(e:Event):void 
		{
			ServiceProxy.instance.dispatchEvent(new Event(ServiceProxy.CLOSE));
			trace("socket断开连接");
		}


		/**
		 * 解析网络数据流
		 */
		private function _parseNetStream():void
		{
			_buffer.position = 1;			
			var packLen:int = _buffer.readShort();
			_buffer.position = 0;
			
			

			if (_buffer.length >= packLen) {
				
				     var packBytes:ByteArray = new ByteArray;
		                 packBytes.endian = Endian.LITTLE_ENDIAN;
					     packBytes.writeBytes(_buffer, 0, packLen);
					
                     var clientByteArray:ByteArray = ProtocolUtils.breakdownPack(packBytes);
						 clientByteArray.endian = Endian.LITTLE_ENDIAN;
						 clientByteArray.position = 0;
						  
					var n:NetMessageBase = new NetMessageBase();
					    n.parse(clientByteArray);

					BufferList.getInstance().add(clientByteArray);						 
						 
					//截取数据后剩下的数据.
					var surplusBytes:ByteArray = new ByteArray();
					    surplusBytes.endian = Endian.LITTLE_ENDIAN;
						surplusBytes.writeBytes(_buffer, packLen);
						_buffer.clear();	
						
						if (surplusBytes.length > 0) { 
					     //剩余数据重新放入Buffer.
						  _buffer.writeBytes(surplusBytes);
						  _parseNetStream();//在处理数据防止粘包有多条数据.
						}
						
				} 
		}
		
		private function _getSocketData(e:ProgressEvent):void
		{
			while (_socket.bytesAvailable > 0) {				
				_buffer.endian = Endian.LITTLE_ENDIAN;				
				//占位
				var tmpByteArr:ByteArray = new ByteArray();
				_socket.readBytes(tmpByteArr);		
				_buffer.position = _buffer.length;			
				_buffer.writeBytes(tmpByteArr);
			    _parseNetStream();	
			}
		}
		 
		public function send(byteArray:ByteArray):void {
			  if(_socket.connected){
			   _socket.writeBytes(byteArray);
			   _socket.flush();
			  }
			}
		
		/**
		 * 独立发送平台TGW数据
		 * @param	tgwData
		 * @param	encoding
		 */
		private function _sendTGWPackData(tgwData:String,encoding:String="GBK"):void {
			   if (_socket.connected && tgwData!=null) {
				   	_socket.writeMultiByte(tgwData,encoding);
					_socket.flush();
				}
			}
			
		public function close():void {
			   _socket.close();
			}
			
		public function get connected():Boolean {
			   if (_socket == null) return false;
			   return _socket.connected;
			}
			
	}

}

